<?php

namespace app\sys\api;

use app\common\logic\Chat;
use app\common\logic\FullUser;
use app\common\logic\KqBuqian;
use app\common\logic\OldRecord;
use app\common\logic\Department;
use my\kaoqin\KaoQin;
use my\wechat\QyErrCode;
use my\wechat\QyWeChat;
use think\Db;

class User extends Common
{
    private $_wechat = null;
    private $_kq = null;

    private function wechat()
    {
        $c = [
            'appid' => c('wx_appid'),
            'appsecret' => c('wx_appsecret')
        ];

        if ($this->_wechat == null)
            $this->_wechat = new QyWeChat($c);

        return $this->_wechat;
    }

    private function kq()
    {
        $c = [
            'appid' => '100018',
            'companyid' => '10840',
            'appsecret' => 'f33e6b9465c2bee511cb5e6a60794e43',
        ];

        if ($this->_kq == null)
            $this->_kq = new KaoQin($c);

        return $this->_kq;
    }

    /**
     * 删除用户
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function delete()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');
        if (!isset($req['id']) || empty($req['id']))
            return $this->error('请选择要删除的数据');

        $id = $req['id'];

        $ret = \app\common\logic\User::destroy(['userid' => ['in', $id]]);
        if ($ret === false)
            return $this->error('删除失败');

        //删除微信企业号成员
        if (is_array($id))
            $ret = $this->wechat()->deleteUsers($id);
        else
            $ret = $this->wechat()->deleteUser($id);

        if ($ret === false)
            return $this->error('删除失败');

        return $this->success('删除成功');
    }

    /**
     * 详情
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function get()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        if (!isset($req['uid']) || empty($req['uid'])) $uid = getUid();
        else $uid = $req['uid'];

        $ret = \app\common\logic\User::get(['userid' => $uid]);

        if (empty($ret)) return $this->error('成员不存在');

        unset($ret['extattr']);

        //成员部门
        $department = Department::where(['id' => $ret['department']])->value('name');
        $ret['department'] = $department;

        return $this->success($ret);
    }

    /**
     * 用户列表
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function lists()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        if (!isset($req['dpt_id']) || empty($req['dpt_id']))
            return $this->error('部门id不能为空');

        if (isset($req['keyword']) && !empty($req['keyword']) && !strstr($req['keyword'], '%'))
            $ret = FullUser::getListByDptIdLike($req['dpt_id'], $req['keyword']);
        else
            $ret = FullUser::getListByDptId($req['dpt_id']);

        return $this->success($ret);
    }

    public function kaoqin()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        if (!isset($req['dpt_id']) || empty($req['dpt_id']))
            return $this->error('部门id不能为空');

        if (!isset($req['start_time']) || empty($req['start_time']))
            return $this->error('开始时间不能为空');

        if (!isset($req['end_time']) || empty($req['end_time']))
            return $this->error('结束时间不能为空');

        $dpt_id = $req['dpt_id'];
//        if ($dpt_id == 1) $dpt_id = 3;

        $start_time = $req['start_time'];
        $end_time = $req['end_time'];

        $dpt_pid = Department::where(['id' => $dpt_id])->value('parentid');
        $time_diff = [strtotime($start_time), strtotime($end_time . ' 23:59:59')];
        $day_must = $this->getDayMust($time_diff);
        $ret = FullUser::getListByDptId($dpt_id);

//        if (in_array($dpt_pid, [0, 1]) && $dpt_id != 6) {
//            $ret['tpl'] = 'btr';
//
//            foreach ($ret['list'] as $k => $user) {
//                $uid = $user['user_id'];
////                $records = FullRecord::getRecordByUidANDTime($uid, $time_diff);
//                $records = Record::getRecordByUidANDTime($uid, $time_diff);
//
//                $day_real = 0;
//                $late_count = 0;
//                $leave_count = 0;
//
//                if (empty($records))
//                    $day_not = $day_must;
//                else
//                    $day_not = $day_must - count($records);
//
//                foreach ($records as $record) {
//                    $log = explode(',', $record['log']);
//
//                    //出错情况
//                    if (empty($log)) {
//                        $day_not++;
//                        continue;
//                    }
//
//                    //打卡次数奇数为未到
//                    if (count($log) % 2 != 0) {
//                        $day_not++;
//                    } else {
//                        $day_real++;
//
//                        $log_first = $log[0];
//                        $log_end = end($log);
//
//                        //计算迟到
//                        $start = strtotime(date('Y-m-d 09:00:00', $log_first));
//                        if ($log_first > $start)
//                            $late_count++;
//
//                        //计算早退
//                        $end = strtotime(date('Y-m-d 18:30:00', $log_end));
//                        if ($log_end < $end)
//                            $leave_count++;
//                    }
//                }
//
//                $ret['list'][$k]['day_must'] = $day_must;
//                $ret['list'][$k]['day_real'] = $day_real;
//                $ret['list'][$k]['day_not'] = $day_not;
//                $ret['list'][$k]['late_count'] = $late_count;
//                $ret['list'][$k]['leave_count'] = $leave_count;
//            }
//        } else {
        $ret['tpl'] = 'group';

        foreach ($ret['list'] as $k => $user) {
            $uid = $user['user_id'];
//                $records = FullRecord::getRecordByUidANDTime($uid, $time_diff);
            $records = OldRecord::getRecordByUidANDTime($uid, $time_diff);

            $day_come = 0;
            $come_count = 0;
            $work_time = 0;

            foreach ($records as $record) {
                $day_come++;
                $log = explode(',', $record['log']);
                $come_count += count($log);
                $work_time += $this->getWorkTime($record['log']);
            }

            $ret['list'][$k]['day_total'] = $day_must;
            $ret['list'][$k]['day_come'] = $day_come;
            $ret['list'][$k]['come_count'] = $come_count;
            $ret['list'][$k]['work_time'] = time_diff2hour($work_time);
        }
//        }
//
        return $this->success($ret);
    }

    /**
     * 用户信息
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function info()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $uid = getUid();
        $data = db('user')->where(['userid' => $uid])->find();

        $user = [
            'avatar' => $data && isset($data['avatar']) ? $data['avatar'] : '',
            'name' => $data && isset($data['name']) ? $data['name'] : ''
        ];

        return $this->success($user);
    }

    /**
     * 根据unix时间差返回天数
     * @param $time_diff
     * @return float|int
     * @author wb <pithyone@vip.qq.com>
     */
    private function getDayMust($time_diff)
    {
        if (!is_array($time_diff)) return 0;
        if (count($time_diff) != 2) return 0;

        $start_unix = $time_diff[0];
        $end_unix = $time_diff[1];
        $day = ($end_unix - $start_unix) / (24 * 60 * 60);

        return round($day);
    }

    /**
     * 根据打卡记录返回工作时长
     * @param $log
     * @return int
     * @author wb <pithyone@vip.qq.com>
     */
    private function getWorkTime($log)
    {
        $work_log = explode(',', $log);
        if (!is_array($work_log)) return 0;    //非数组
        if (count($work_log) < 1) return 0;    //数组为空

        $time_diff = 0;
        $odd = array();
        $even = array();

        foreach ($work_log as $k => $v) {
            if ($k % 2 == 0) $odd[] = $v;
            else $even[] = $v;
        }

        foreach ($odd as $k => $v) {
            if (!empty($even[$k])) {
                $time_diff += ($even[$k] - $odd[$k]);
            }
        }

        return $time_diff;
    }

    /**
     * 同步微信通讯录
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function sync()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $sync_dept_id = 1;

        //获取全部成员
        $ret_get_user = $this->wechat()->getUserListInfo($sync_dept_id, 1);
        if ($ret_get_user === false) return $this->error(QyErrCode::getErrText($this->wechat()->errCode));

        if (isset($ret_get_user['userlist']) && !empty($ret_get_user['userlist'])) {
            $userlist = $ret_get_user['userlist'];

            //遍及userid
            $wx_userids = [];
            foreach ($userlist as $val) {
                if (!empty($val['userid']) && !in_array($val['userid'], $wx_userids))
                    $wx_userids[] = $val['userid'];
            }

            //对比本地用户
            $local_dept_child_id = Department::getChildIds($sync_dept_id);
            $local_userids = \app\common\logic\User::where(['department' => ['in', $local_dept_child_id]])->column('userid');

            $user_del = array_values(array_diff($local_userids, $wx_userids));
            $user_add = array_values(array_diff($wx_userids, $local_userids));
            $user_eq = array_values(array_intersect($wx_userids, $local_userids));

            $error = [];

            //删除
            if (!empty($user_del)) {
                $chat_del = [];
                foreach ($user_del as $val) {
                    $local_dept_id = \app\common\logic\User::where(['userid' => $val])->value('department');
                    $chat_del[$local_dept_id][] = $val;
                }

                foreach ($chat_del as $k => $val) {
                    //删除群聊
//                    $chat = Chat::get(['dpt_id' => $k]);
                    $chat = Chat::get(['optional' => ['like', "%,{$k},%"]]);
                    $chatid = $chat['chatid'];

                    $ret_chat = $this->chat_del_user($chatid, $val);
                    if (!is_array($val)) $val = [$val];
                    if ($ret_chat === false) $error[] = '群聊' . $chat['real_name'] . '删除用户' . implode(',', $val) . '失败';
                }

                $ret_user_del = \app\common\logic\User::where(['userid' => ['in', $user_del]])->delete();
                if ($ret_user_del === false) $error[] = '批量删除用户失败';
            }

            //新增
            //获取新增用户列表
            $userlist_add = [];
            $chat_add = [];
            foreach ($userlist as $val) {
                if (!empty($val['userid']) && in_array($val['userid'], $user_add)) {
                    $data_add = [];

                    if (isset($val['userid']) && !empty($val['userid'])) $data_add['userid'] = $val['userid'];
                    else $data_add['userid'] = '';
                    if (isset($val['name']) && !empty($val['name'])) $data_add['name'] = $val['name'];
                    else $data_add['name'] = '';
                    if (isset($val['department']) && !empty($val['department'])) {
                        if (is_array($val['department'])) {
                            $data_add['department'] = $val['department'][0];
                            if (count($val['department']) > 1) $error[] = '用户' . $val['userid'] . '新增时存在多部门';
                        } else  $data_add['department'] = $val['department'];
                    } else $data_add['department'] = '';
                    if (isset($val['position']) && !empty($val['position'])) $data_add['position'] = $val['position'];
                    else $data_add['position'] = '';
                    if (isset($val['mobile']) && !empty($val['mobile'])) $data_add['mobile'] = $val['mobile'];
                    else $data_add['mobile'] = '';
                    if (isset($val['gender']) && !empty($val['gender'])) $data_add['gender'] = $val['gender'];
                    else $data_add['gender'] = '';
                    if (isset($val['email']) && !empty($val['email'])) $data_add['email'] = $val['email'];
                    else $data_add['email'] = '';
                    if (isset($val['weixinid']) && !empty($val['weixinid'])) $data_add['weixinid'] = $val['weixinid'];
                    else $data_add['weixinid'] = '';
                    if (isset($val['avatar']) && !empty($val['avatar'])) $data_add['avatar'] = $val['avatar'];
                    else $data_add['avatar'] = '';
                    if (isset($val['status']) && !empty($val['status'])) $data_add['status'] = $val['status'];
                    else $data_add['status'] = 4;
                    if (isset($val['extattr']) && !empty($val['extattr'])) $data_add['extattr'] = serialize($val['extattr']);
                    else $data_add['extattr'] = '';

                    $userlist_add[] = $data_add;

                    $chat_add[$data_add['department']][] = $val['userid'];
                }
            }

            //同步群聊
            foreach ($chat_add as $k => $val) {
//                $chat = Chat::get(['dpt_id' => $k]);
                $chat = Chat::get(['optional' => ['like', "%,{$k},%"]]);
                $chatid = $chat['chatid'];
                $ret_chat_add = $this->chat_add_user($chatid, $val);
                if (!is_array($val)) $val = [$val];
                if ($ret_chat_add === false) $error[] = '群聊' . $chat['real_name'] . '新增用户' . implode(',', $val) . '失败';
            }

            if (!empty($userlist_add)) {
                $user_logic = new \app\common\logic\User();
                $ret_user_add = $user_logic->addList($userlist_add);
                if ($ret_user_add === false) $error[] = '批量新增用户失败';
            }

            //更新
            //获取更新用户列表
            $chat_del = [];
            $chat_add = [];
            $userlist_update = [];
            foreach ($userlist as $val) {
                if (!empty($val['userid']) && in_array($val['userid'], $user_eq)) {
                    if (isset($val['department']) && !empty($val['department'])) {
                        if (is_array($val['department'])) {
                            $val['department'] = $val['department'][0];
                            if (count($val['department']) > 1) $error[] = '用户' . $val['userid'] . '更新时存在多部门';
                        }
                    }

                    if (isset($val['extattr']) && !empty($val['extattr'])) $val['extattr'] = serialize($val['extattr']);

                    //判断部门是否更改，同步群聊
                    $local_dept_id = \app\common\logic\User::where(['userid' => $val['userid']])->value('department');
                    if ($local_dept_id != $val['department']) {
                        $chat_del[$local_dept_id][] = $val['userid'];
                        $chat_add[$val['department']][] = $val['userid'];
                    }

                    $userlist_update[] = $val;
                }
            }

            //删除旧群聊
            foreach ($chat_del as $k => $val) {
//                $chat = Chat::get(['dpt_id' => $local_dept_id]);
                $chat = Chat::get(['optional' => ['like', "%,{$k},%"]]);
                $chatid = $chat['chatid'];
                $ret_chat = $this->chat_del_user($chatid, $val);
                if (!is_array($val)) $val = [$val];
                if ($ret_chat === false) $error[] = '群聊' . $chat['real_name'] . '删除用户' . implode(',', $val) . '失败';
            }


            //新群聊
            foreach ($chat_add as $k => $val) {
//                $chat = Chat::get(['dpt_id' => $val['department']]);
                $chat = Chat::get(['optional' => ['like', "%,{$k},%"]]);
                $chatid = $chat['chatid'];
                $ret_chat = $this->chat_add_user($chatid, $val);
                if (!is_array($val)) $val = [$val];
                if ($ret_chat === false) $error[] = '群聊' . $chat['real_name'] . '新增用户' . implode(',', $val) . '失败';
            }

            if (!empty($userlist_update)) {
                foreach ($userlist_update as $val) {
                    $ret_user_update = \app\common\logic\User::update($val, ['userid' => $val['userid']]);
                    if ($ret_user_update === false) $error[] = '更新用户' . $val . '失败';
                }
            }

            if (!empty($error)) return $this->error('同步微信通讯录失败，请稍后重试', 4001, $error);
        }

        return $this->success('同步微信通讯录成功');
    }

    /**
     * 新增会话成员
     * @param $chatid
     * @param $uid
     * @return bool
     * @author wb <pithyone@vip.qq.com>
     */
    private function chat_add_user($chatid, $uid)
    {
        $users = [];
        if (!is_array($uid)) $users[] = $uid;
        else $users = array_merge($users, $uid);

        if (!empty($chatid)) {
            //新增企业会话成员
            $ret = \my\wechat\Chat::addUser($chatid, $users);

            //新增本地会话成员
            $chat_logic = new Chat();
            $ret_add_user = $chat_logic->addUsers($chatid, $users);

            if ($ret === false || $ret_add_user === false) return false;
        }

        return true;
    }

    /**
     * 删除会话成员
     * @param $chatid
     * @param $uid
     * @return array|bool
     * @author wb <pithyone@vip.qq.com>
     */
    private function chat_del_user($chatid, $uid)
    {
        $users = [];
        if (!is_array($uid)) $users[] = $uid;
        else $users = array_merge($users, $uid);

        if (!empty($chatid)) {
            //删除企业会话成员
            $ret = \my\wechat\Chat::delUser($chatid, $users);

            //删除本地会话成员
            $chat_logic = new Chat();
            $ret_add_user = $chat_logic->delUsers($chatid, $users);

            if ($ret_add_user === false) return false;
        }

        return true;
    }

    /**
     * 推送通讯录到考勤机
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function sync_kq()
    {
        if (!$this->checkAuth())
            return $this->_error;

        //获取全部成员
        $ret_kq_user = $this->kq()->userList();
        if ($ret_kq_user === false) return $this->error($this->kq()->errMsg);

        if (isset($ret_kq_user['list']) && !empty($ret_kq_user['list'])) {
            $userlist = $ret_kq_user['list'];

            //遍及userNo
            $kq_userids = [];
            foreach ($userlist as $val) {
                if (!empty($val['userNo']) && !in_array($val['userNo'], $kq_userids))
                    $kq_userids[] = $val['userNo'];
            }

            //对比本地用户
            $local_userids = \app\common\logic\User::column('userid');

            $user_del = array_values(array_diff($kq_userids, $local_userids));
            $user_add = array_values(array_diff($local_userids, $kq_userids));
            $user_eq = array_values(array_intersect($local_userids, $kq_userids));

            $error = [];

            //删除
            if (!empty($user_del)) {
                $ret_user_del = $this->kq()->userDelete(['list' => $user_del]);
                if ($ret_user_del === false) $error[] = '批量删除用户失败';
            }

            //新增
            //获取新增用户列表
            $userlist_add = [];
            foreach ($user_add as $val) {
                $local_user = \app\common\logic\User::get(['userid' => $val]);
                $dept_id = $local_user['department'];
                $dept_pid = Department::getPidById($dept_id);
                $deptId = $this->_get_kq_id($dept_pid);

                $data_add = ['userNo' => $val, 'name' => $local_user['name'], 'phone' => $local_user['mobile']];
                if (!empty($deptId)) $data_add['deptId'] = $deptId;

                $userlist_add[] = $data_add;
            }

            if (!empty($userlist_add)) {
                $ret_user_add = $this->kq()->userAdd(['list' => $userlist_add]);
                if ($ret_user_add === false) $error[] = '批量新增用户失败';
            }

            //更新
            //获取更新用户列表
            $userlist_update = [];
            foreach ($user_eq as $val) {
                $local_user = \app\common\logic\User::get(['userid' => $val]);
                $dept_id = $local_user['department'];
                $dept_pid = Department::getPidById($dept_id);
                $deptId = $this->_get_kq_id($dept_pid);

                $data_update = ['userNo' => $val, 'name' => $local_user['name'], 'phone' => $local_user['mobile']];
                if (!empty($deptId)) $data_update['deptId'] = $deptId;

                $userlist_update[] = $data_update;
            }

            if (!empty($userlist_update)) {
                $ret_user_update = $this->kq()->userUpdate(['list' => $userlist_update]);
                if ($ret_user_update === false) $error[] = '批量更新用户失败';
            }

            if (!empty($error)) return $this->error('推送通讯录到考勤机失败，请稍后重试', 4001, $error);
        }

        return $this->success('推送通讯录到考勤机成功');
    }

    private function _get_kq_id($dept_pid)
    {
        $deptId = 0;
        $department_id_kq_id = c('department_id_kq_id');
        foreach ($department_id_kq_id as $v) {
            if ($dept_pid == $v['id']) {
                $deptId = $v['name'];
                break;
            }
        }
        return $deptId;
    }

    /**
     * 用户列表
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function bq_info()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        if (!isset($req['keyword']) || empty($req['keyword']) || strstr($req['keyword'], '%'))
            return $this->error('请输入要搜索的信息');

        $keyword = $req['keyword'];
        $ret = FullUser::where(['name|moblie' => ['like', "%{$keyword}%"]])->order('user_id')->select();

        return $this->success($ret);
    }

    /**
     * 补签详情
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function get_bq()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        if (!isset($req['id']) || empty($req['id']))
            return $this->error('请选择要查看的补签信息');

        $id = $req['id'];

        $ret = KqBuqian::get(['id' => $id]);
        if (empty($ret))
            return $this->error('补签信息不存在');

        return $this->success($ret);
    }

    /**
     * 补签列表
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function lists_bq()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        $where = [];

        if (isset($req['source']) && !empty($req['source']))
            $where['source'] = $req['source'];

        if (isset($req['status']) && in_array($req['status'], [-1, 0, 1]))
            $where['status'] = $req['status'];

        $ret = KqBuqian::getList($where, 'create_time desc');

        return $this->success($ret);
    }

    /**
     * 模拟补签
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function buqian()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');
        $sp_uid = getUid();

        if (!isset($req['uid']) || empty($req['uid']))
            return $this->error('请填写补签人uid');

        if (!isset($req['time']) || empty($req['time']))
            return $this->error('请填写补签时间');

        $uid = $req['uid'];

        $data['uid'] = $uid;
        $data['time'] = strtotime($req['time']);

        $info = \app\common\logic\User::get(['userid' => $uid]);
        if (empty($info))
            return $this->error('用户不存在');

        $data['avatar'] = $info['avatar'];
        $data['name'] = $info['name'];
        $data['mobile'] = $info['mobile'];

        $dept_id = $info['department'];
        $dept = Department::where(['id' => $dept_id])->value('name');
        $data['dept'] = $dept;

        $data['source'] = 'pc';
        $data['sp_uid'] = $sp_uid;
        $data['sp_name'] = \app\common\logic\User::where(['userid' => $sp_uid])->value('name');
        $data['sp_time'] = time();
        $data['status'] = 1;

        if (isset($req['reason']) && !empty($req['reason']))
            $data['reason'] = $req['reason'];

        $data['create_time'] = time();
        $data['update_time'] = time();

        $ret = Db::name('kq_buqian')->insert($data);

        if ($ret === false)
            return $this->error('补签失败');

        OldRecord::create(['userId' => $uid, 'time' => strtotime($req['time']), 'from' => 'pc']);

        return $this->success('补签成功');
    }
}